import io
import logging
import os
import random
import sys
import traceback

from PIL import Image
from facade.loggerfacade import get_filelogger, get_streamlogger
from facade.mysqlfacade import MysqlUtiles
from xjlibrary.database_moudel.simple.mysqlclient import MySqlDbConnect, SelctSqlFromDB, ExeSqlList
from xjlibrary.mrequest.baserequest import BaseRequest, USER_AGENTS
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "acs", "download", "cover")

HEADERS = {'User-Agent': random.choice(USER_AGENTS)}

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")

listurl = ["/isbn/9780841239999", "/isbn/9780841230460"]

BookBaseUrl = "https://pubs.acs.org"

keytransformdicts = {"port": "db_port", "host": "db_host", "passwd": "db_pw", "user": "db_user",
                     "db": "db_name",
                     "chartset": "db_charset"}


def SelectListFromDB():
    global nCount, ListSqls
    sSql = "SELECT `url`,`coverurl` FROM `ebook` where coverstat=0"
    rows = myutil.SelectFromDB(sSql)
    return rows


def get_url(url):
    count = 0
    while count < 5:
        print("url is : {}".format(url))
        BoolResult, errString, r = BaseRequest(url, headers=HEADERS, endstring="", timeout=30)
        if not BoolResult:
            print("出现错误 ，请检查")
            count += 1
        return r
    return None


def Img2Jpg(buf, dstFile):
    print('Img2Jpg %s ...' % dstFile)

    exMsg = ''
    try:
        srcImg = Image.open(io.BytesIO(buf))
        dstImg = srcImg.resize((108, 150), Image.ANTIALIAS).convert('RGB')
        dstImg.save(dstFile, 'JPEG')
    except:
        exMsg = '* %s' % traceback.format_exc()
        print(exMsg)
    if exMsg:
        return False

    return True


def save_file(outfile, r):
    if os.path.exists(outfile):
        print("文件存在{}".format(outfile))
        return
    if Img2Jpg(r.content, outfile):
        print("保存图片成功")
    else:
        print("保存文件失败,请检查")
        sys.exit(-1)


def get_list_url(rows):
    for url, coverurl in rows:
        print(url)
        outfile = url.replace("/isbn/", "") + ".jpg"
        if not os.path.exists(sPath):
            os.makedirs(sPath)
        outfile = BaseDir.get_new_path(sPath, outfile)
        if os.path.exists(outfile):
            sql = "update `ebook` set `coverstat`=1 where url = '{}'".format(url)
            myutil.ExeSqlToDB(sql, errExit=True)
            continue
        urlimage = BookBaseUrl + coverurl
        r = get_url(urlimage)
        if r is None:
            continue
        print("下载完成开始解析并下载保存图片")
        save_file(outfile, r)
        sql = "update `ebook` set `coverstat`=1 where url = '{}'".format(url)
        myutil.ExeSqlToDB(sql, errExit=True)


def main(logger1: logging.Logger):
    global logger, myutil
    logger = logger1
    myutil = MysqlUtiles(configfile, "db", keytransformdicts=keytransformdicts, logger=logger)
    rows = SelectListFromDB()
    get_list_url(rows)


if __name__ == "__main__":
    logger1 = get_filelogger("./logs")
    main(logger1)
